package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired(required = false)
    private CategoryMapper categoryMapper;
    @Autowired(required = false)
    private DishMapper dishMapper;
    @Autowired(required = false)
    private SetmealMapper setMealMapper;


    //保存类别
    @Override
    public void save(Category category) {
        log.info("+++++++保存了");
        categoryMapper.save(category);

    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<Category> findByPage(int page, int pageSize) {
        //1. 设置开始页与页面大小
        PageHelper.startPage(page, pageSize);
        //2. 查找所有的类别
        List<Category> categoryList = categoryMapper.findAll();
        //3. 创建PageInfo
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        Page<Category> pageResult = new Page<>(pageInfo.getList(), pageInfo.getTotal(), page, pageSize);
        return pageResult;
    }

    /**
     * 根据Id删除类别
     *
     * @param id
     */
    @Override
    public void removeById(Long id) {
        Long count = dishMapper.findDishWithCategory(id);
        if (count > 0) {
            throw new ClassCastException("该类别关联了菜品");
        }
        count = setMealMapper.findSetMealWithCategory(id);
        if (count > 0) {
            throw new ClassCastException("该类别关联了菜品");

        }
        categoryMapper.deleteById(id);
    }

    @Override
    public void updateById(Category category) {
        categoryMapper.updateById(category);
    }

    @Override
    public List<Category> findAll(Integer type) {
        return categoryMapper.findByType(type);
    }

}
